package com.example.sunmiv1.adapter;

import android.content.Context;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.GoodsStoreRetreatInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.ContentValues.TAG;

public class PurchaseRefundAddingAdapter extends RecyclerView.Adapter<PurchaseRefundAddingAdapter.praViewHolder> {

    private List<GoodsStoreRetreatInfo.DataBean> mList;
    private CheckBoxListener mCheckBoxListener;
    private Context mContext;
    private String pricePermission;// 門店查看價格權限
//    private PurchaseRefundAddingAdapter.EditTextListener mEditTextListener;

    public PurchaseRefundAddingAdapter(Context context, List<GoodsStoreRetreatInfo.DataBean> list) {
        super();
        mList = list;
        mContext = context;
        ACache aCache = ACache.get(context);
        pricePermission = aCache.getAsString("showPrice");
    }

    @Override
    public int getItemViewType(int position) {
        return super.getItemViewType(position);
    }

    @Override
    public praViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_purchase_refund_add, parent, false);
        return new praViewHolder(v);
    }

    @Override
    public void onBindViewHolder(praViewHolder holder, final int position) {
        holder.setIsRecyclable(false);  //  防止重用item  導致item渲染混亂
        holder.goodName.setText(mList.get(position).getGoods_name());
        Tools.hideViewInItem(mList.get(position).getSku_name(), holder.skuName);

        holder.goodsNumber.setText(mList.get(position).getGoods_number());
        holder.goodsCode.setText(mList.get(position).getGoods_code());
        holder.infoPurQuantity.setText(String.valueOf(mList.get(position).getPurchase_num()));
        holder.infoReturnedQuantity.setText(String.valueOf(mList.get(position).getRetreat_num()));
        holder.infoCanReturnQuantity.setText(String.valueOf(mList.get(position).getSurplus_num()));
        holder.infoPurchasePrice.setText(String.valueOf(mList.get(position).getPurchase_price()));
        holder.infoOrderNumber.setText(mList.get(position).getOrder_number());
//        holder.goodsUnit.setText(mList.get(position).getCompany());

        holder.infoPurBuildDate.setText(mList.get(position).getBuild_date());
        holder.infoPurQualityGuaranteePeriod.setText(mList.get(position).getQuality_guarantee_period());

        Tools.hideViewInItem(mList.get(position).getCompany(), holder.goodsUnit);
        holder.edRetreatPrice.setText(String.valueOf(mList.get(position).getRetreat_price()));
        LogUtil.i("getRetreat_price()" + mList.get(position).getRetreat_price() + "");
        final TextWatcher erpTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                limitDecimal(s, holder.edRetreatPrice);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (holder.edRetreatPrice.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        mList.get(position).setRetreat_price(Double.valueOf(s.toString()));
                        LogUtil.i("adapter：寫入Retreat_price" + s.toString());
                    } else {
                        mList.get(position).setRetreat_price(0.0);
                    }
                }

            }
        };
        setETFocusChangeListener(position, erpTextWatcher, holder.edRetreatPrice);

        holder.edRetreatNumAct.setText(mList.get(position).getRetreat_num_act() == null ? "" : mList.get(position).getRetreat_num_act() + "");
        LogUtil.i("getRetreat_num_act()" + mList.get(position).getRetreat_num_act() + "");
        final TextWatcher ernTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                limitDecimal(s, holder.edRetreatNumAct);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (holder.edRetreatNumAct.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        mList.get(position).setRetreat_num_act(Double.valueOf(s.toString()));
                        LogUtil.i("adapter：寫入Retreat_num_act" + s.toString());
                    } else
                        mList.get(position).setRetreat_num_act(0.0);
                }
            }
        };
        setETFocusChangeListener(position, ernTextWatcher, holder.edRetreatNumAct);

        holder.edRetreatItemNote.setText(mList.get(position).getRemarks());
        final TextWatcher erinTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (holder.edRetreatItemNote.hasFocus()) {
                    if (!TextUtils.isEmpty(s.toString().trim()))
                        mList.get(position).setRemarks(s.toString());
                    else
                        mList.get(position).setRemarks("");
                }
            }
        };
        setETFocusChangeListener(position, erinTextWatcher, holder.edRetreatItemNote);

        holder.addGoodsCheck.setChecked(mList.get(position).isChecked());
        holder.addGoodsCheck.setOnCheckedChangeListener((buttonView, isChecked) -> mCheckBoxListener.setCheckBoxListener(isChecked, position));

        if ("2".equals(pricePermission)) {
            ((View) holder.infoPurchasePrice.getParent()).setVisibility(View.GONE);
            ((View) holder.edRetreatPrice.getParent()).setVisibility(View.GONE);
        }
        if ("1".equals(mList.get(position).getSerial_number_state())) {
            holder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            holder.edRetreatNumAct.setVisibility(View.GONE);
            Log.e(TAG, "onBindViewHolder: 商品的庫存========" + mList.get(position).getRetreat_num_act());
//            if (TextUtils.isEmpty(mList.get(position).getRetreat_num_act())) {
//                holder.inventorySearchAdapterInventoryTv.setText("0");
//            } else {
            holder.inventorySearchAdapterInventoryTv.setText(mList.get(position).getRetreat_num_act()+"");
//            }
        } else {
            holder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            holder.edRetreatNumAct.setVisibility(View.VISIBLE);
        }
        holder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(position);
            }
        });
    }

    private Choose choose;
    public void setChoose(Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index);
    }

    @Override
    public int getItemCount() {
        return mList == null ? 0 : mList.size();
    }

    static class praViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.add_goods_check)
        CheckBox addGoodsCheck;
        @BindView(R.id.goods_name)
        TextView goodName;
        @BindView(R.id.layout_goods_name)
        RelativeLayout layoutGoodsName;
        @BindView(R.id.sku_name)
        TextView skuName;
        @BindView(R.id.layout_sku_name)
        RelativeLayout layoutSkuName;
        @BindView(R.id.goods_number)
        TextView goodsNumber;
        @BindView(R.id.layout_goods_number)
        RelativeLayout layoutGoodsNumber;
        @BindView(R.id.goods_code)
        TextView goodsCode;
        @BindView(R.id.layout_goods_code)
        RelativeLayout layoutGoodsCode;
        @BindView(R.id.info_pur_quantity)
        TextView infoPurQuantity;
        @BindView(R.id.info_returned_quantity)
        TextView infoReturnedQuantity;
        @BindView(R.id.info_can_return_quantity)
        TextView infoCanReturnQuantity;
        @BindView(R.id.info_purchase_price)
        TextView infoPurchasePrice;
        @BindView(R.id.info_order_number)
        TextView infoOrderNumber;
        @BindView(R.id.ed_retreat_price)
        EditText edRetreatPrice;
        @BindView(R.id.ed_retreat_num_act)
        EditText edRetreatNumAct;
        @BindView(R.id.ed_retreat_item_note)
        EditText edRetreatItemNote;
        @BindView(R.id.goods_unit)
        TextView goodsUnit;
        @BindView(R.id.info_pur_build_date)
        TextView infoPurBuildDate;
        @BindView(R.id.info_pur_quality_guarantee_period)
        TextView infoPurQualityGuaranteePeriod;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;

        public praViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }

    public static interface CheckBoxListener {
        void setCheckBoxListener(boolean isChecked, int position);
    }

    public void setCBListener(CheckBoxListener cbListener) {
        this.mCheckBoxListener = cbListener;
    }

//    public interface EditTextListener{
//        void setEditTextListener(String s,int position);
//    }
//
//    public void setETListener(PurchaseRefundAddingAdapter.EditTextListener etListener){
//        mEditTextListener=etListener;
//    }

    /**
     * 限制小數點後三位
     *
     * @param charSequence
     * @param num
     */
    private void limitDecimal(CharSequence charSequence, EditText num) {
        if (charSequence.toString().contains(".")) {
            if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                num.setText(charSequence.toString().
                        substring(0, charSequence.toString().length() - 1));
                num.setSelection(charSequence.length() - 1);
            } else {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                    charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                    num.setText(charSequence);
                    num.setSelection(charSequence.length());
                }
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            num.setText(charSequence);
            num.setSelection(2);
        }

        if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                num.setText(charSequence.subSequence(1, 2));
                num.setSelection(1);
            }
        }
    }

    /**
     * 設置edittext焦點的監聽器
     *
     * @param position
     * @param textWatcher
     * @param editText
     */
    private void setETFocusChangeListener(int position, TextWatcher textWatcher, EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                ((EditText) v).addTextChangedListener(textWatcher);
                Log.e("addTextChanged", position + "");
            } else {
                ((EditText) v).removeTextChangedListener(textWatcher);
                Log.e("removeTextChanged", position + "");
            }
        });
    }

}
